package com.luban.securitysession.config;

import com.luban.securitysession.strategy.MyExpiredSessionStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 *
 *
 * @author : fujc-dev@qq.com
 * @motto : talk is cheap, show me the code. salute the future!
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("fox")
                .password("{noop}123456").authorities("admin,user");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin();

        http.sessionManagement()
                //SessionCreationPolicy
                //ALWAYS                如果session不存在总是需要创建
                //NEVER                   如果需要就创建一个session（默认）登录时
                //IF_REQUIRED         Spring Security 将不会创建session，但是如果应用中其他地方创建了session，那么Spring Security将会使用它
                //STATELESS             Spring Security将绝对不会创建session，也不使用session。并且它会暗示不使用cookie，所以每个请求都需要重新进行身份验证。这种无状态架构适用于REST API及其无状态认证机制。
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .invalidSessionUrl("/session/invalid")
                // 最大会话数量
                .maximumSessions(1)
                // 配置会话过期策略
                .expiredSessionStrategy(new MyExpiredSessionStrategy())
                //阻止用户第二次登录
                .maxSessionsPreventsLogin(true);

        http.authorizeRequests()
                .antMatchers("/login", "/session/invalid").permitAll()
                .anyRequest().authenticated();
        http.csrf().disable();

    }
}
